package com.panopset.gui.container;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class PanNumericOnlyField extends PanTextField {

    public PanNumericOnlyField(int cols, String borderTitle,
            String toolTipText, String defaultValue) {
        super(cols, borderTitle, toolTipText, defaultValue);
    }

    /*
     * from http://www.devx.com/tips/Tip/25194
     */
    public static class NumberFilterDocument extends PlainDocument {
        private StringBuffer __scratchBuffer;

        public NumberFilterDocument() {
            __scratchBuffer = new StringBuffer();
        }

        public void insertString(int offset, String text, AttributeSet aset)
                throws BadLocationException {
            if (text == null)
                return;

            __scratchBuffer.setLength(0);

            // Reject all strings that cause the contents of the field not
            // to be a valid number (i.e., string representation of a double)
            try {
                __scratchBuffer.append(getText(0, getLength()));
                __scratchBuffer.insert(offset, text);
                // Kludge: Append a 0 so that leading decimal points
                // and signs will be accepted
                __scratchBuffer.append('0');
            } catch (BadLocationException ble) {
                ble.printStackTrace();
                return;
            } catch (StringIndexOutOfBoundsException sioobe) {
                sioobe.printStackTrace();
                return;
            }

            try {
                Double.parseDouble(__scratchBuffer.toString());
            } catch (NumberFormatException nfe) {
                // Resulting string will not be number, so reject it
                return;
            }

            super.insertString(offset, text, aset);
        }
        private static final long serialVersionUID = com.panopset.Util.VERSION_SERIAL_NUMBER;
    }

    protected void init() {
        super.init();
        getInnerComponent().setDocument(new NumberFilterDocument());
    }
}
